<template>
  <view class="invite-accpet">
    <image class="user-img" :src="`https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/img_${gender === '2' ? 'default' : gender === 'O' ? 'girl' : 'boy'}.png`" />
    <view class="user-name">
      {{ familyName }}
    </view>

    <view class="accpet-content">
      <view class="accpet-title">
        邀请你加入{{ familyName }}组
      </view>
      <template v-if="!isInvalidation">
        <up-form
          ref="formRef"
          label-position="top"
          :model="formData"
          :label-width="100"
          :rules="rules"
        >
          <up-form-item
            label="手机号"
            prop="userInfo.accountNumber"
            :border-bottom="false"
          >
            <up-input
              v-model="formData.userInfo.accountNumber"
              placeholder="请输入手机号"
              border="bottom"
              clearable
              placeholder-class="placeholder-style"
              placeholder-style="color: #888"
            />
          </up-form-item>

          <up-form-item
            label="验证码"
            prop="userInfo.validCode"
            :border-bottom="false"
          >
            <up-input
              v-model="formData.userInfo.validCode"
              placeholder="请输入验证码"
              border="bottom"
              clearable
              placeholder-class="placeholder-style"
              placeholder-style="color: #888"
            >
              <template #suffix>
                <up-code
                  ref="uCodeRef"
                  seconds="60"
                  change-text="X秒重新获取"
                  @change="codeChange"
                />
                <up-button
                  type="primary"
                  :plain="true"
                  :text="tips"
                  shape="circle"
                  @tap="getCode"
                />
              </template>
            </up-input>
          </up-form-item>
        </up-form>

        <view class="login-info">
          <up-checkbox
            v-model:checked="checked"
            used-alone
            size="28rpx"
            active-color="#4AAAF8"
            inactive-color="#999"
          />
          <text class="info-text">
            我已阅读并同意
          </text>
          <text class="info-link" @click="handleShowPopup(1)">
            《隐私协议》
          </text>
          <text class="info-link" @click="handleShowPopup(2)">
            《用户协议》
          </text>
        </view>
        <button class="login-btn" @tap="submit">
          加入
        </button>
      </template>

      <button v-else class="disabled-btn">
        邀请已失效
      </button>
    </view>
  </view>
  <AgreePrivacy v-model:model-value="modelValue" :type="modelType" />
  <ConfirmOverlay v-model:show="show" :title="isSuccess ? '您已成功接受邀请' : '您已是该家庭账户的成员，无需再次加入哦～'" confirm-text="我已知晓" :show-cancel-btn="false" @confirm="handleConfirm" />
</template>

<script lang="ts" setup>
import type uCode from 'uview-plus/components/u-code/u-code.vue';
import type uForm from 'uview-plus/components/u-form/u-form.vue';
import { useUserStore } from '@/store';
import type { LoginParams } from '@/api/user/type';
import { addFamilyMember, getFamilyShareInfo } from '@/api/my';
import { setStudentList, setToken } from '@/utils/auth';

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
});

const store = useUserStore();

const isInvalidation = ref<boolean>(false); // 是否邀请过
const familyCode = ref('');
const familyName = ref('');
const familyRoleName = ref('');
const gender = ref('');
const code = ref('');

const getData = () => {
  getFamilyShareInfo({ code: code.value }).then((res) => {
    isInvalidation.value = !res.status;
    if (res.result) {
      familyCode.value = res.result.split('&')[0];
      familyRoleName.value = res.result.split('&')[1];
    }
  });
};

onLoad((option: any) => {
  familyName.value = option.familyName;
  gender.value = option.gender;
  code.value = option.code;

  getData();
});

const formData = ref<{ userInfo: LoginParams }>({
  userInfo: {
    loginType: 'customer_user_login_phone',
    accountNumber: '',
    validCode: '',
  },
});

const rules = ref({
  'userInfo.accountNumber':
    { required: true, message: '请输入正确的手机号', pattern: /^1[3-9]\d{9}$/, trigger: ['blur', 'change'] },
  'userInfo.validCode':
    { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
});

const modelValue = ref<boolean>(false); // 隐私协议弹窗
const modelType = ref<number>(0); // 协议类型
const checked = ref<boolean>(false);

const handleShowPopup = (type: number) => {
  modelType.value = type;
  modelValue.value = true;
};

const tips = ref<string>();
const formRef = ref<InstanceType<typeof uForm>>();

const codeChange = (text: string) => {
  tips.value = text;
};

const uCodeRef = ref<InstanceType<typeof uCode> | null>(null);
const getCode = () => {
  formRef.value.validateField('userInfo.accountNumber').then(() => {
    if (uni.$u.test.mobile(formData.value.userInfo.accountNumber)) {
      if (uCodeRef.value?.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          // 通知验证码组件内部开始倒计时
          uCodeRef.value?.start();
        }, 1000);
        store.getCode(formData.value.userInfo.accountNumber);
      }
      else {
        uni.$u.toast('倒计时结束后再发送');
      }
    }
  });
};

const show = ref<boolean>(false);
const isSuccess = ref<boolean>(false);
const submit = () => {
  if (!checked.value) {
    uni.$u.toast('请先同意隐私政策');
    return;
  }
  formRef.value.validate().then((valid: any) => {
    if (valid) {
      addFamilyMember({
        familyRoleName: familyRoleName.value,
        familyCode: familyCode.value,
        mobile: formData.value.userInfo.accountNumber,
        shareCode: code.value,
        msgCode: formData.value.userInfo.validCode,
      }).then((res) => {
        if (res.status === 0) { // 重复加入
          show.value = true;
          isSuccess.value = false;
        }
        else {
          show.value = true;
          isSuccess.value = true;
          if (res.result.token) {
            setToken(res.result.token);
          }
          if (res.result.studentList.length) {
            setStudentList(res.result.studentList);
          }
        }
      });
    }
  }).catch(() => {
  });
};

const handleConfirm = () => {
  show.value = false;
  uni.reLaunch({ url: '/pages/tab/home/index' });
};
</script>

<style lang="scss" scoped>
.invite-accpet {
  padding: 36rpx 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;

  .user-img {
    width: 88rpx;
    height: 88rpx;
  }

  .user-name {
    padding-top: 14rpx;
    padding-bottom: 26rpx;
    font-weight: bold;
    font-size: 32rpx;
    color: #000000;
    line-height: 48rpx;
  }

  .accpet-content {
    width: 100%;
    padding: 56rpx 52rpx;
    background: #fff;
    border-radius: 20rpx;

    .accpet-title {
      padding-bottom: 55rpx;
      font-size: 28rpx;
      color: #000000;
      line-height: 42rpx;
      text-align: center;
    }

    .login-info {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      line-height: 28rpx;

      .info-text {
        color: #999;
      }

      .info-link {
        color: #4AAAF8;
      }
    }

    .login-btn {
      height: 92rpx;
      margin: 100rpx 0 20rpx 0;
      border-radius: 46rpx;
      font-size: 32rpx;
      line-height: 92rpx;
      background: linear-gradient( 90deg, rgba(246,216,108,0.98) 0%, #FFC122 100%);
      color: #fff;
    }

    .disabled-btn {
      height: 92rpx;
      margin: 425rpx 0 20rpx 0;
      border-radius: 46rpx;
      font-size: 32rpx;
      line-height: 92rpx;
      background: #EBEBEB;
      color: #B6B6B6;
    }
  }
}
:deep(.u-form-item__body) {
  padding: 30rpx 0 !important;
}

:deep(.u-form-item__body__left__content__label) {
  font-size: 24rpx !important;
  line-height: 28rpx;
  color: #666 !important;
  padding-bottom: 10rpx;
}

:deep(.u-input) {
  padding: 12rpx 0 !important;
}

:deep(.u-reset-button) {
  height: 56rpx !important;
  color: #4AAAF8 !important;
  border-color: #4AAAF8 !important;
}

:deep(.u-checkbox__icon-wrap) {
  width: 30rpx !important;
  height: 30rpx !important;
}
</style>
